<template>
	<view class="flex column space-between addAccompany width-full">
		<view class="userTitle flex box-sizing  space-between items-center">
			<!-- <view class="box-sizing paddingLeft-30">
				<u-icon @click="uni.navigateBack()" name="arrow-left" :size="25" ></u-icon>
			</view>
			<view style="margin-left: calc(0px - 20px - 15rpx );" class="flex box-sizing  flex-center items-center height-full">
				<view class="fontSize-30 weight-700 marginRight-10">
					{{stuentInfo.name+'(学法记录)'}}
				</view>
			</view>
			<view class=""></view> -->
			<view class="box-sizing paddingLeft-30" style="width: 120rpx;">
				<u-icon @click="uni.navigateBack()" name="arrow-left" :size="25"></u-icon>
			</view>
			<view style="flex: 1;padding-left: calc(10rpx);" class=" flex box-sizing  flex-center items-center height-full">
				<view class="fontSize-30 weight-700 marginRight-10 text-hidden">
					{{stuentInfo.name+' ('+stuentInfo.text+')'}}
				</view>
			</view>
			<view class="right box-sizing paddingRight-50">
				<view @click="$u.throttle(submit, 500)" class="submit flex flex-center items-center fontSize-27 color-white">
					提交
				</view>
			</view>
		</view>
		<view class="crads  box-sizing padding-30 ">
			<u--form
					labelPosition="left"
					:model="form"
					:rules="rules"
					ref="uForm"
					:labelWidth = "90"
					>
						<u-form-item
							label="日期"
							prop="record_time"
							borderBottom
							ref="item1"
							required
							@click="datetimeShow = true;"
						>
							<u--input
								:customStyle = "{'pointer-events':'none'}"
								v-model="form.record_time"
								disabled
								disabledColor="#ffffff"
								placeholder="请选择日期"
								border="none"
							></u--input>
							<u-icon
								slot="right"
								name="arrow-right"
							></u-icon>
						</u-form-item>
						<u-form-item
							v-if="form.type == 1"
								label="心理"
								prop="good_habit_name"
								borderBottom
								required
								@click="method_idShow = true;"
								ref="item1"
						>
							<u--input
									:customStyle = "{'pointer-events':'none'}"
									v-model="form.good_habit_name"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择心理"
									border="none"
							></u--input>
							<u-icon
									slot="right"
									name="arrow-right"
							></u-icon>
						</u-form-item>
						<u-form-item
							v-if="form.type == 2"
								label="习惯"
								prop="bad_habit_name"
								required
								borderBottom
								@click="method_idShow = true;"
								ref="item1"
						>
							<u--input
									:customStyle = "{'pointer-events':'none'}"
									v-model="form.bad_habit_name"
									disabled
									disabledColor="#ffffff"
									placeholder="请选择习惯"
									border="none"
							></u--input>
							<u-icon
									slot="right"
									name="arrow-right"
							></u-icon>
						</u-form-item>
						<u-form-item
								label="备注"
								prop="mark"
								borderBottom
								ref="item1"
						>
							<u--textarea v-model="form.mark" placeholder="请输入备注" ></u--textarea>
						</u-form-item>
						<u-form-item label="附件" prop="image" borderBottom ref="item1">
							<!-- #ifdef H5  -->
							<u-upload accept="file" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :maxCount="1"></u-upload>
							<!-- #endif -->
							<!-- #ifdef APP-PLUS -->
							<u-upload accept="image" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :maxCount="1"></u-upload>
							<!-- #endif -->
							<!-- #ifdef MP-WEIXIN -->
							<u-upload accept="all" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :maxCount="1"></u-upload>
							<!-- #endif -->
						</u-form-item>
						
					</u--form>
		</view>
		<!-- <view class="operation flex box-sizing space-around items-center">
			<view @click="$u.throttle(submit, 500)" class="flex flex-center items-center fontSize-30 color-white">
				提交
			</view>
		</view> -->
		<!-- <u-datetime-picker
			:show="datetimeShow"
			v-model="form.px_date"
			mode="date"
			@cancel = "datetimeShow = false"
			@confirm = "datetimeClick"
		></u-datetime-picker> -->
		<u-calendar :minDate="minDate" :show="datetimeShow" closeOnClickOverlay @confirm="datetimeClick" @close = "datetimeShow = false"></u-calendar>
		<!-- @confirm = "(e)=>form.px_date = e" -->
		<!-- <u-datetime-picker
			:show="start_timeShow"
			v-model="form.start_time"
			@cancel = "start_timeShow = false"
			@confirm = "(e)=>timeConfirm(e,'start_time','start_timeShow')"
			mode="time"
		></u-datetime-picker>
		<u-datetime-picker
			:show="end_timeShow"
			v-model="form.end_time"
			mode="time"
			@cancel = "end_timeShow = false"
			@confirm = "(e)=>timeConfirm(e,'end_time','end_timeShow')"
		></u-datetime-picker> -->
		<u-picker :show="start_timeShow" :columns="sjds" keyName="label" closeOnClickOverlay @close="start_timeShow = false" @cancel="start_timeShow = false"
			@confirm="timeConfirm"></u-picker>
		<u-picker :show="subject_idShow" :columns="subject_idData" keyName="name" closeOnClickOverlay @close="subject_idShow = false" @cancel = "subject_idShow = false" @confirm = "subjectChange" ></u-picker>
		<!-- <u-picker :show="method_idShow" :columns="method_idData" @cancel = "method_idShow = false" @confirm = "method_idChange" ></u-picker> -->
		<u-popup bgColor = "#fff" :round = "10" :show="method_idShow" @close="treeClose" @open="method_idShow = true">
			<view class="popupTreeBox">
				<DaTreeVue2
					  ref="DaTreeRef"
					  :data="asyncTreeData"
					  labelField="label"
					  valueField="value"
					  showCheckbox
					  :defaultCheckedKeys="defaultCheckedKeysValue"
					  @change="handleTreeChange"
					  @expand="handleExpandChange" />
			</view>
		</u-popup>
	</view>
</template>

<script>
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	const date = d.getDate()
	export default {
		components:{
			DaTreeVue2
		},
		data() {
			return {
				minDate: `${year}-${month-1}-${date}`,
				defaultCheckedKeysValue: [],
				asyncTreeData:[],
				stuentInfo:{},
				fileList1:[],
				studentSubjectData:[],
				datetimeShow:false,
				start_timeShow:false,
				end_timeShow:false,
				subject_idShow:false,
				method_idShow:false,
				type:1,
				subject_idData:[
					[]
				],
				sjds:[[]],
				method_idData:[
					[]
				],
				form:{
					record_time:`${year}-${month}-${date}`,
					good_habit:[],
					good_habit_name:'',
					bad_habit:[],
					bad_habit_name:'',
					mark:''
					
				},
				rules:{
					'record_time': {
						type: 'string',
						required: true,
						message: '请选择日期',
						trigger: ['change']
					},
					'start_timeName': {
						type: 'string',
						required: true,
						message: '请选择巡视时间',
						trigger: ['change']
					},
					'subject_name': {
						type: 'string',
						required: true,
						message: '请选择科目',
						trigger: ['change']
					},
				}
			};
		},
		onLoad(op) {
			this.form.student_id = op.student_id
			this.form.type = op.type
			this.type = op.type
			this.stuentInfo['name'] = op.name
			this.stuentInfo['text'] = op.type==1?'添加心理':'添加习惯'
			// this.stuentInfo['name'] = op.name
			this.stuentInfo['student_id'] = op.student_id
			// this.stuentInfo['learn_mode'] = op.learn_mode
			this.getInfo()
			// let date = new Date()
			// let year = date.getFullYear();
			// let month = date.getMonth() + 1;
			// let day = date.getDate();
			// let hour = date.getHours();
			// let minute = date.getMinutes();
			// let second = date.getSeconds();
			// let defaultTime = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
			// this.form.px_date =  defaultTime
			// this.form.start_time = date.getHours()+':'+date.getMinutes()
			// this.form.end_time = date.getHours()+':'+date.getMinutes()
		},
		methods:{
			getInfo(){
				let that = this
				this.$home.gethabit({type:this.type}).then(res=>{
					// that.infoList = res
					that.asyncTreeData = res.habitlist?res.habitlist:[]
					// that.grade_nameData = res.grade_ids?[[...res.grade_ids]]:[[]],
					// that.pxtypeData = res.pxtypes?[[...res.pxtypes]]:[[]]
				})
			},
			studentSubject(){
				this.$home.studentSubject({student_id:0}).then(res=>{
					this.subject_idData[0] = res.data
					console.log(res.data,6666)
				})
			},
			treeClose(){
				this.defaultCheckedKeysValue = this.form.type==1?[...this.form.good_habit]:[[...this.form.bad_habit]]
				this.method_idShow = false
			},
			handleTreeChange(allSelectedKeys, currentItem) {
			  console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
			  this.form.type==1?this.form.good_habit = [...allSelectedKeys]:this.form.bad_habit = [...allSelectedKeys]
			  let checks = this.$refs.DaTreeRef.getCheckedNodes()
			  this.form.chapter_name = ''
			  this.form.type==1?this.form.good_habit_name = '':this.form.bad_habit_name = ''
			  // originItem
			  if(checks){
			  		this.setVal(checks,this.form.type==1?'good_habit_name':'bad_habit_name')
			  }
			},
			setVal(list,key,labelKey='label'){
				if(list&&list.length>0){
					list.map(e=>{
						this.form[key] +=e.label+';'
					})
				}
			},
			handleExpandChange(expand, currentItem) {
			  console.log('handleExpandChange ==>', expand, currentItem)
			},
			datetimeClick(e){
				if(e&&e.length>0){
					this.form.record_time = e[0]
				}
				this.datetimeShow = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					this.form.fileway = event.file&&event.file.type?event.file.type:'image'
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$uploadUrl+'Upload/upload', // 仅为示例，非真实的接口地址
						// url: 'http://bbsf.test/api/Upload/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							upload_config_id: 1
						},
						header: {
							token: uni.getStorageSync('token'),
							// 'content-type': 'multipart/form-data'
						},
						success: (res) => {
							resolve(JSON.parse(res.data).data)
						},
						fail:(err)=>{
							console.log(err,999)
						}
					});
				})
			},
			submit(){
				let that = this
				let form = this.form
				if(!form.record_time||form.record_time == ''){
					return uni.showToast({
						title:'请选择日期',
						icon:'none'
					})
				}
				// if(!form.start_timeName||form.start_timeName == ''){
				// 	return uni.showToast({
				// 		title:'请选择巡视时间',
				// 		icon:'none'
				// 	})
				// }
				// if(!form.subject_name||form.subject_name == ''){
				// 	return uni.showToast({
				// 		title:'请选择科目',
				// 		icon:'none'
				// 	})
				// }
				// this.$refs.uForm.validate().then(res => {
					
					let defaultUser = uni.getStorageSync('userInfo')
					let params = {
						user_id:defaultUser.user_id,
						dept_id:defaultUser.dept_id,
						comp_no:defaultUser.comp_no
					}
					form.good_habit = form.good_habit?form.good_habit.join():''
					form.bad_habit = form.bad_habit?form.bad_habit.join():''
					params = {...params,...form}
					params.files = this.fileList1
					this.$home.attainmentAdd(params).then(res=>{
						if(res.status == 200){
							uni.showToast({
								title:'提交成功!',
								icon:'none'
							})
							uni.navigateBack()
							
							let pages = getCurrentPages()
							let backPage = pages&&pages.length>0?pages[pages.length-2].$vm:{}
							if(backPage){
								backPage.setCurrent(that.type)
							}
						}else{
							uni.$u.toast('提交失败')
						}
					})
					
					
				// }).catch(errors => {
				// 	uni.$u.toast('校验失败')
				// })
			},
		
		}
	}
</script>

<style lang="scss" scoped>
.addAccompany{
	height: 100vh;
	box-sizing: border-box;
	.popupTreeBox{
		width: 100%;
		height: 60vh;
		padding-top: 50rpx;
		overflow-y: auto;
		padding-left: 30rpx;
		padding-right: 30rpx;
		box-sizing: border-box;
	}
	.userTitle{
		width: 100%;
		height: 120rpx;
		box-sizing: border-box;
		padding-top: var(--status-bar-height);
		background-color: #fff;
		border-bottom: 1rpx solid #ededed;
	}
	.crads{
		width: 100%;
		height: calc(100vh - 120rpx - 120rpx);
		overflow-y: auto;
		
		.card{
			width: calc(100% - 60rpx);
			background-color: #f7f7f7;
			color:#333;
		}
	}
	.operation{
		width: 100%;
		height: 120rpx;
		// background-color: #f7f7f7;
		background-color: #fff;
		view{
			width: 80%;
			border-radius: 500rpx;
			padding: 20rpx 0;
			border: 1rpx solid #fff;
			background-color: #ea9700a1;
		}
	}
	.right{
		
	}
	.submit{
		width: 120rpx;
		
		padding: 5rpx 0rpx;
		border-radius: 10rpx;
		border: 1rpx solid #fff;
		background-color: #ea9700a1;
	}
}
</style>
